package top.oauth2.gateway.component;

import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.oauth2.common.result.CommonResult;

import java.nio.charset.StandardCharsets;


/**
 * 服务器身份验证入口点
 * 自定义返回结果：没有登录或token过期时
 * @author xphu
 * @version 1.0
 * @date 2021/8/30 14:35
 */
@Component
public class RestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    /**
     * Initiates the authentication flow
     *
     * @param exchange
     * @param e
     * @return {@code Mono<Void>} to indicate when the request for authentication is complete
     */
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String body = JSONUtil.toJsonStr(CommonResult.unauthorized(e.getMessage()));
        DataBuffer dataBuffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }
}
